﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Drawing;


using agsXMPP;
using agsXMPP.protocol.client;

using agsXMPP.protocol.iq.roster;
using agsXMPP.protocol.iq.vcard;

namespace jabberclient1
{
	
	
	public class ListViewStuff
	{
		public string imgPath { get; set; }
		public string jid { get; set; }
		public System.Drawing.Image rosterimgPath { get; set; }
		
		public Jid tojid{get;set;}
		
		public ListViewStuff( string imgPath, string jid,System.Drawing.Image rosterimgPath,Jid tojid)
		{
			this.imgPath = imgPath;
			this.jid = jid;
			this.rosterimgPath=rosterimgPath;
			this.tojid=tojid;
		}
	}
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		
        delegate void OnMessageDelegate(object sender, agsXMPP.protocol.client.Message msg);
		delegate void OnPresenceDelegate(object sender, Presence pres);
		XmppClientConnection myclient;
		public List<ListViewStuff> ListViewDataSource { get; set; }
		System.Drawing.Image emptyavatar;//=System.Drawing.Image.FromFile("default-avatar.jpg");
		
		public MainWindow()
		{
			this.InitializeComponent();
			//emptyavatar=new System.Drawing.Bitmap("busy.gif");
			//emptyavatar=System.Drawing.Image.FromFile("away.gif");
			emptyavatar=System.Drawing.Image.FromFile("default-avatar.jpg");
			myclient=new XmppClientConnection();
            myclient.OnLogin+=new ObjectHandler(myclient_OnLogin);
            myclient.OnAuthError += new XmppElementHandler(myclient_OnAuthError);
            myclient.OnError+=new ErrorHandler(myclient_OnError);
            myclient.OnRosterStart += new ObjectHandler(myclient_OnRosterStart);
            myclient.OnRosterItem += new XmppClientConnection.RosterHandler(myclient_OnRosterItem);
            myclient.OnRosterEnd += new ObjectHandler(myclient_OnRosterEnd);
			
            myclient.OnPresence += new PresenceHandler(myclient_OnPresence);
            myclient.OnMessage += new MessageHandler(myclient_OnMessage);
			
			
			
			
			
			// Insert code required on object creation below this point.
			DataContext = this;
			ListViewDataSource = new List<ListViewStuff>();
			
		}
		
		void myclient_OnMessage(object sender, Message msg)
        {   
			if (this.lstRoster.Dispatcher.Thread!=System.Threading.Thread.CurrentThread)
			{	
				lstRoster.Dispatcher.Invoke(new OnMessageDelegate(myclient_OnMessage), new object[] { sender, msg });
				return;
			}
			

			//MessageBox.Show(msg.From.Bare+" "+Util.ChatForms.ContainsKey(msg.From.Bare.ToLower()));
			if(!Util.ChatForms.ContainsKey(msg.From.Bare.ToLower()))
			{
				ChatWindow chatwin=new ChatWindow(msg.From,myclient);
			
			chatwin.Show();
				chatwin.IncomingMessage(msg);
				
			}
				
        }

        void myclient_OnPresence(object sender, Presence pres)
        {
           // MessageBox.Show("Presence : " + pres.From.ToString() +" : " +pres.Show.ToString() +" : "+ pres.Status);
		
			
			
			if (this.lstRoster.Dispatcher.Thread!=System.Threading.Thread.CurrentThread)
			{	
				lstRoster.Dispatcher.Invoke(new OnPresenceDelegate(myclient_OnPresence),new object[]{this,pres});
				return;
			}
			
			
			
			ListViewStuff currrent_roster= ListViewDataSource.Find(delegate(ListViewStuff lst){return lst.jid==pres.From.Bare;});
			
			if(currrent_roster!=null && pres!=null)
			{
				
				if(pres.Type==PresenceType.unavailable)
				{
					currrent_roster.imgPath="offline.gif";
				}
				else
				{
			if(pres.Show==ShowType.NONE)
			{
				currrent_roster.imgPath="online.gif";
			}
			if(pres.Show==ShowType.dnd)
			{
				currrent_roster.imgPath="busy.gif";
			}
			if(pres.Show==ShowType.away)
			{
				currrent_roster.imgPath="away.gif";
			}
				}
			}
			//lstRoster.ItemsSource=null;
			//lstRoster.ItemsSource=ListViewDataSource;
			lstRoster.Items.Refresh();
        }

        void myclient_OnRosterEnd(object sender)
        {
            //MessageBox.Show("Roster end!!");
        }

        void myclient_OnRosterItem(object sender, RosterItem item)
        {
			
			if (this.lstRoster.Dispatcher.Thread!=System.Threading.Thread.CurrentThread)
			{	
				lstRoster.Dispatcher.Invoke(new agsXMPP.XmppClientConnection.RosterHandler(myclient_OnRosterItem),new object[]{this,item});
				return;
			}
			
			
			VcardIq viq = new VcardIq(IqType.get, new Jid(item.Jid.Bare));
		     String packetiq=viq.Id;
				
			
			
			ListViewDataSource.Add(new ListViewStuff("offline.gif", item.Jid.Bare,emptyavatar,item.Jid));
			         
			myclient.IqGrabber.SendIq(viq, new IqCB(VcardResult), null);
			lstRoster.Items.Refresh();
        }
		
		private void VcardResult(object sender, IQ iq, object data)
		{
			if (this.lstRoster.Dispatcher.Thread!=System.Threading.Thread.CurrentThread)
			{	
				lstRoster.Dispatcher.Invoke(new IqCB(VcardResult),new object[]{sender,iq,data});
				return;
			}
		
			
			
			System.Drawing.Image rosteravatar=emptyavatar;
            if (iq.Type == IqType.result)
			{
				Vcard vcard = iq.Vcard;
				if (vcard!=null)
				{
					Photo photo = vcard.Photo;
					
					if (photo != null)
						rosteravatar	= vcard.Photo.Image;
				}
                
                
			}
			
			ListViewStuff currrent_roster= ListViewDataSource.Find(delegate(ListViewStuff lst){return lst.jid==iq.From.Bare;});
			
			if(iq!=null)
			{
				currrent_roster.rosterimgPath=rosteravatar;
				
			}
			lstRoster.Items.Refresh();
		}

        void myclient_OnRosterStart(object sender)
        {
            //MessageBox.Show("Roster Start!!");
        }

        void myclient_OnAuthError(object sender, agsXMPP.Xml.Dom.Element e)
        {
            MessageBox.Show("Login Failed!!");
        }

        void myclient_OnLogin(object sender)
        {
			if (this.lblusrname.Dispatcher.Thread!=System.Threading.Thread.CurrentThread)
			{	
				lblusrname.Dispatcher.Invoke(new ObjectHandler(myclient_OnLogin), new object[] { sender});
				return;
			}
           
			MessageBox.Show("Login successful"+myclient.Username);
			lblusrname.Content=myclient.Username;
			
	   }

        void myclient_OnError(object sender, Exception ex)
        {
            MessageBox.Show("Error Access Denied!!!");
              
        }

		private void ListView_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: Add event handler implementation here.
			
			
		}

		private void lstRoster_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			
		}

		private void lstRoster_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			
		}

		private void lstRoster_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			
		}

		private void lstRoster_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
		{
			ListViewStuff ljid=(ListViewStuff)lstRoster.SelectedItem;
			
			ChatWindow chatwin=new ChatWindow(ljid.tojid,myclient);
			
			chatwin.Show();
		}

		private void statustxtbox_LostFocus(object sender, System.Windows.RoutedEventArgs e)
		{
			MessageBox.Show("Lost Focus");
			myclient.Status=statustxtbox.Text;
			myclient.SendMyPresence();
		}

		private void statustxtbox_LostMouseCapture(object sender, System.Windows.Input.MouseEventArgs e)
		{
			// TODO: Add event handler implementation here.
		}

		private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			Jid sndjid = new Jid(usernametxt.Text);
            myclient.Server = sndjid.Server;
			myclient.Username=sndjid.User;
            myclient.AutoResolveConnectServer = true;
			myclient.Password=passwordbox.Password;
            myclient.Open();
		}

		
	}
}